package xq.gwt.mvc.model;

import java.util.Date;
import xq.gwt.mvc.util.DateFormatUtil;

public class DatePropertyModel extends AbstractPropertyModel {
		
	private static final long serialVersionUID = 3956995290326960372L;
	private Date value;
	private String dateFormat = "dd/MM/yyyy";
	

	public Date getValue() {
		return value;
	}

	public void setValue(Date value) {
		Date oldValue = this.value;
		this.value = value;
		setHasError(false);
		notifyPropertyChanged(oldValue, value);
	}
	
	public String getDateFormat() {
		return dateFormat;
	}

	public void setDateFormat(String dateFormat) {
		this.dateFormat = dateFormat;
	}

	@Override
	public String getText() {
		if(getValue() == null)
			return null;
        
        return DateFormatUtil.getDateFormatter().format(getValue(), dateFormat);		
	}

	@Override
	public void setText(String text) throws ConversionException {
		setHasError(false);
		if((text == null) ||(text.equals(""))){
			setValue(null);
			return;
		}
		Date dateVal;
		try {			
            dateVal =  DateFormatUtil.getDateFormatter().parse(text, dateFormat);
		} catch (Exception e) {
			ConversionException ce = new ConversionException(e.getLocalizedMessage());
			ce.initCause(e);
			setHasError(true);			
			throw ce;
		}
		
		setValue(dateVal);
		
	}
	
	public Object getObjectValue() {		
		return getValue();
	}

	public Class getPropertyType() {		
		return Date.class;
	}
}
